package home;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;

import net.ck.hzq.R;
import net.ck.hzq.TobuyApplication;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import Bean.HomeTargetBean;
import Utils.HelloWordModel;
import Utils.ScreenUtil;
import Utils.SharedPrefStore;
import adapter.DividerAdapter;
import base.BaseBiz;
import base.BaseFra;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;
import dao.BaseOutput;
import dao.HomeBannerBean;
import dao.HomeDataInput;
import dao.HomePageOutput;
import event.MessageEvent;
import event.NetErrorEvent;
import home.adapter.BenefitAdapter;
import home.adapter.CenterBannerAdapter1;
import home.adapter.HomeTargetAdapter;
import home.adapter.HotRecommendAdapter;
import home.adapter.MerchantServiceAdapter;
import home.adapter.NewsAdapter;
import home.adapter.TopBannerAdapter;
import home.adapter.TopFixedAdapter;
import home.adapter.TopLineAdapter;
import home.adapter.TopTargetAdapter;
import retrofit2.Call;
import retrofit2.Response;
import ui.activity.home.SearchInfoAct;
import ui.activity.home.biz.HomeBiz;
import ui.activity.mine.MessageAct;
import ui.activity.profit.KF5CustomerAct;
import ui.model.CreditCardsBean;
import ui.model.NoticeInfo;
import util.LogUtils;
import util.StringUtils;
import util.ToastUtils;
import widget.ADEnity;


/**
 * by BF00233 on 2018/12/10.
 */
public class NewHomeFragment extends BaseFra {
    private TopFixedAdapter topFixedAdapter;
    private TopTargetAdapter topTargetAdapterAdapter;
    private TopBannerAdapter topBannerAdapter;
    private TopLineAdapter topLineAdapter;
    private CenterBannerAdapter1 centerBannerAdapter;
    private BenefitAdapter benefitAdapter;
    private HotRecommendAdapter hotRecommendAdapter;
    private NewsAdapter newsAdapter;

    private ImageView supportonline_img;
    private TextView number;
    private RelativeLayout homeMessage;
    private LinearLayout top_backimg;
    private RelativeLayout system_layout;
    private TextView systemCha;
    private TextView audioTextView;
    private EditText search;
    RecyclerView recyclerView;
    PtrClassicFrameLayout ptr;
    private int mDistance = 0;
    private int maxDistance = 255;//当距离在[0,255]变化时，透明度在[0,255之间变化,0为完全透明]
    private int alpha = 0;
    HomeBiz homeBiz;
    SharedPrefStore store;
    String messageId = "";
    String messageSaveId = "";
    String messageContent = "";
    String messageSaveContent = "";


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_new, container, false);
    }

    /**
     * 设置标题栏背景透明度
     */
    private void setSystemBarAlpha() {
//        if (alpha > 255) {
            top_backimg.getBackground().setAlpha(255);
//        } else {
//            top_backimg.getBackground().setAlpha(alpha);
//        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        store = new SharedPrefStore();
        messageId = store.getString("messageId", "");
        messageContent = store.getString("messageSaveContent", "");
        homeBiz = new HomeBiz();
        ptr = view.findViewById(R.id.pull_refresh_ptr);
        homeMessage = view.findViewById(R.id.top_question);
        top_backimg = view.findViewById(R.id.top_backimg);
        number = view.findViewById(R.id.message_number);
        search = view.findViewById(R.id.top_ss);
        supportonline_img = view.findViewById(R.id.supportonline_img);
        system_layout = view.findViewById(R.id.home_system_layout);
        systemCha = view.findViewById(R.id.home_system_cha);
        audioTextView = view.findViewById(R.id.fragment_audio_text);
        audioTextView.setSelected(true);
        //设置顶部渐变色初始颜色
        top_backimg.setBackgroundColor(Color.parseColor("#0CA6F0"));
        recyclerView = view.findViewById(R.id.recycler_view);
        VirtualLayoutManager virtualLayoutManager = new VirtualLayoutManager(view.getContext());
        recyclerView.setLayoutManager(virtualLayoutManager);
        recyclerView.setItemAnimator(null);
        DelegateAdapter delegateAdapter = new DelegateAdapter(virtualLayoutManager);
        recyclerView.setAdapter(delegateAdapter);
        setSystemBarAlpha();//初始化渐变色为0
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mDistance += dy;
                float percent = mDistance * 1f / maxDistance;//百分比
                alpha = (int) (percent * 255);
                setSystemBarAlpha();
            }
        });
        homeMessage.setOnClickListener(v -> {
            if (!TobuyApplication.isAuthed()) {
                ToastUtils.shortToast("请先进行实名认证");
                return;
            }
            Intent intent = new Intent(getActivity(), MessageAct.class);
            startActivity(intent);
        });
        search.setOnClickListener(v -> {
            if (!TobuyApplication.isAuthed()) {
                ToastUtils.shortToast("请先进行实名认证");
                return;
            }
            Intent intent = new Intent(getActivity(), SearchInfoAct.class);
            startActivity(intent);

            LogUtils.d("");
        });
        supportonline_img.setOnClickListener(v -> {
            if (!TobuyApplication.isAuthed()) {
                ToastUtils.shortToast("请先进行实名认证");
                return;
            }
            Intent intent = new Intent(getActivity(), KF5CustomerAct.class);
            startActivity(intent);

            LogUtils.d("");
        });


        audioTextView.setOnClickListener(v -> {
            LogUtils.d("");
        });
        systemCha.setOnClickListener(v -> {
            if (system_layout.getVisibility() == View.VISIBLE) {
                system_layout.setVisibility(View.GONE);
                store.putString("messageId", messageSaveId);
                store.putString("messageSaveContent", messageSaveContent);
                messageId = messageSaveId;
                messageContent = messageSaveContent;
            }
        });
        //搜索固定布局
//        topFixedAdapter= new TopFixedAdapter(getContext());
//        delegateAdapter.addAdapter(topFixedAdapter);
//        topFixedAdapter.show(true);

//        //实际是中间的灰色空白部分
//        NewDriverAdapter dividerAdapter0 = new NewDriverAdapter(getContext(), ScreenUtil.dip2px(view.getContext(), 60));
//        delegateAdapter.addAdapter(dividerAdapter0);
//        dividerAdapter0.show(true);

        //顶部4个标签
        // 2019 5.20隐藏头部四个标签 by 方俊松
        topTargetAdapterAdapter = new TopTargetAdapter(getContext());
        delegateAdapter.addAdapter(topTargetAdapterAdapter);

        //原来顶部轮播图
//        topBannerAdapter = new TopBannerAdapter(getContext());
//        delegateAdapter.addAdapter(topBannerAdapter);

//        DividerAdapter dividerAdapter1 = new DividerAdapter(getContext(), ScreenUtil.dip2px(view.getContext(), 10));
//        delegateAdapter.addAdapter(dividerAdapter1);
//        dividerAdapter1.show(true);

        HomeTargetAdapter targetAdapter = new HomeTargetAdapter(getContext());
        delegateAdapter.addAdapter(targetAdapter);
        targetAdapter.setupData(getTargetList());

        DividerAdapter dividerAdapter2 = new DividerAdapter(getContext(), ScreenUtil.dip2px(view.getContext(), 1));
        delegateAdapter.addAdapter(dividerAdapter2);
        dividerAdapter2.show(true);

        // 头条播报
        topLineAdapter = new TopLineAdapter(getContext());
        delegateAdapter.addAdapter(topLineAdapter);

        DividerAdapter dividerAdapter3 = new DividerAdapter(getContext(), ScreenUtil.dip2px(view.getContext(), 10));
        delegateAdapter.addAdapter(dividerAdapter3);
        dividerAdapter3.show(true);

        centerBannerAdapter = new CenterBannerAdapter1(getContext());
        delegateAdapter.addAdapter(centerBannerAdapter);

        DividerAdapter dividerAdapter4 = new DividerAdapter(getContext(), ScreenUtil.dip2px(view.getContext(), 10));
        delegateAdapter.addAdapter(dividerAdapter4);
        dividerAdapter4.show(true);

        // 本月收益
        benefitAdapter = new BenefitAdapter(getContext());
        delegateAdapter.addAdapter(benefitAdapter);

        DividerAdapter dividerAdapter5 = new DividerAdapter(getContext(), ScreenUtil.dip2px(view.getContext(), 10));
        delegateAdapter.addAdapter(dividerAdapter5);
        dividerAdapter5.show(true);

        // 商户服务
        MerchantServiceAdapter serviceAdapter = new MerchantServiceAdapter(getContext());
        delegateAdapter.addAdapter(serviceAdapter);

        DividerAdapter dividerAdapter6 = new DividerAdapter(getContext(), ScreenUtil.dip2px(view.getContext(), 10));
        delegateAdapter.addAdapter(dividerAdapter6);
        dividerAdapter6.show(true);

//        // 热门推荐
//        hotRecommendAdapter = new HotRecommendAdapter(getContext());
//        delegateAdapter.addAdapter(hotRecommendAdapter);
//
//        DividerAdapter dividerAdapter8 = new DividerAdapter(getContext(), ScreenUtil.dip2px(view.getContext(), 10));
//        delegateAdapter.addAdapter(dividerAdapter8);
//        dividerAdapter8.show(true);

//        // 热门新闻
//        NewsTitleAdapter newsTitleAdapter = new NewsTitleAdapter(getContext());
//        delegateAdapter.addAdapter(newsTitleAdapter);
//        newsAdapter = new NewsAdapter(getContext());
//        delegateAdapter.addAdapter(newsAdapter);
//        DividerAdapter dividerAdapter7 = new DividerAdapter(getContext(), ScreenUtil.dip2px(view.getContext(), 10));
//        delegateAdapter.addAdapter(dividerAdapter7);
//        dividerAdapter7.show(true);
        ptr.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getNews();
                showHeadLine();
                getCradList();
            }
        });
        ptr.autoRefresh(true);
    }

    private void getNews() {
        HomeDataInput param = new HomeDataInput();
        param.customId = store.getString("id", "0");
        Call<BaseOutput<HomePageOutput>> userMsgCall = HelloWordModel.getInstance(getActivity()).getHomePage(param);
        userMsgCall.enqueue(new retrofit2.Callback<BaseOutput<HomePageOutput>>() {
            @Override
            public void onResponse(@NonNull Call<BaseOutput<HomePageOutput>> call, @NonNull
                    Response<BaseOutput<HomePageOutput>> response) {
                try {
                    BaseOutput<HomePageOutput> body = response.body();
                    if (body != null && body.msg.equals("success") && body.data != null) {
                        if (topTargetAdapterAdapter != null) {
                            topTargetAdapterAdapter.setupData(getTopTargetList(), body.data.banner1.get(0).getBanner(), body.data.banner1.get(0).getUrl());
                        }
//                    if (topBannerAdapter != null) {
//                        topBannerAdapter.setUpBanner(body.data.banner1);
//                    }
                        if (centerBannerAdapter != null) {
                            List<List<HomeBannerBean>> lists = new ArrayList<>();
                            for (int i = 0; i < body.data.getBanner2().size(); i++) {
                                if (!StringUtils.isEmpty(body.data.getBanner2().get(i).get(0).getImgBanner())) {
                                    lists.add(body.data.getBanner2().get(i));
                                }
                            }
                            centerBannerAdapter.setUpBanner(lists);
                        }
                        if (benefitAdapter != null) {
                            benefitAdapter.setupData(body.data.monsy);
                        }


                        if (newsAdapter != null) {
                            newsAdapter.setupData(body.data.news);
                        }
                        intervalTopLine(body.data.headlines);
                    } else {
                        Toast.makeText(getActivity(), StringUtils.isEmpty(body.msg) ? "" : body.msg, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ptr.onRefreshComplete();
            }

            @Override
            public void onFailure(Call<BaseOutput<HomePageOutput>> call, Throwable t) {
                Log.d("test", t.toString());
                ptr.onRefreshComplete();
            }
        });
    }


    private void intervalTopLine(List<String> headlines) {
        List<ADEnity> list = new ArrayList<>();
        for (int i = 0; i < headlines.size(); i++) {
            ADEnity adenity = new ADEnity("重", headlines.get(i), "");
            list.add(adenity);
        }
        topLineAdapter.setData(list);
    }


    private List<HomeTargetBean> getTargetList() {
        List<HomeTargetBean> targetList = new ArrayList<>();
        HomeTargetBean targetBean = new HomeTargetBean();
        targetBean.iconResId = R.drawable.homeicon1;
        targetBean.title = "在线商城";
        targetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.drawable.homeicon2;
        targetBean.title = "终端管理";
        targetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.drawable.homeicon3;
        targetBean.title = "积分兑换";
        targetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.drawable.homeicon4;
        targetBean.title = "在线客服";
        targetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.drawable.homeicon5;
        targetBean.title = "我的收益";
        targetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.drawable.homeicon6;
        targetBean.title = "当日收益";
        targetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.drawable.homeicon7;
        targetBean.title = "业绩排名";
        targetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.drawable.homeicon8;
        targetBean.title = "活动专区";
        targetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.drawable.homeicon9;
        targetBean.title = "商学院";
        targetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.drawable.homeicon10;
        targetBean.title = "我要分享";
        targetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.drawable.homeicon11;
        targetBean.title = "每日签到";
        targetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.drawable.homeicon12;
        targetBean.title = "了解更多";
        targetList.add(targetBean);
        return targetList;
    }

    private List<HomeTargetBean> getTopTargetList() {
        List<HomeTargetBean> toptargetList = new ArrayList<>();
        HomeTargetBean targetBean = new HomeTargetBean();
        targetBean.iconResId = R.mipmap.sy_qd;
        targetBean.title = "每日签到";
        toptargetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.mipmap.sy_drsy;
        targetBean.title = "当日收益";
        toptargetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.mipmap.sy_yjph;
        targetBean.title = "业绩排名";
        toptargetList.add(targetBean);
        targetBean = new HomeTargetBean();
        targetBean.iconResId = R.mipmap.sy_ques;
        targetBean.title = "了解更多";
        toptargetList.add(targetBean);
        return toptargetList;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        homeBiz.onDestory();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getNumber() == 0) {
            number.setVisibility(View.INVISIBLE);
        } else {
            number.setText(event.getNumber() + "");
            number.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 显示头条信息
     */
    private void showHeadLine() {
        homeBiz.getHomeNewsList(new BaseBiz.Callback<NoticeInfo>() {
            @Override
            public void onSuccess(NoticeInfo noticeInfoItemsInfo) {
                if (!StringUtils.isEmpty(noticeInfoItemsInfo.getContent())) {
                    if (!messageId.equals(noticeInfoItemsInfo.getId()) || !messageContent.equals(noticeInfoItemsInfo.getContent())) {
                        String info = "";
                        for (int i = 0; i < 3; i++) {
                            info += noticeInfoItemsInfo.getContent() + "              ";
                        }
                        audioTextView.setText(info);
//                        system_layout.setVisibility(View.VISIBLE);
                    } else {
                        system_layout.setVisibility(View.GONE);
                    }
                    messageSaveId = noticeInfoItemsInfo.getId();
                    messageSaveContent = noticeInfoItemsInfo.getContent();
                } else {
                    system_layout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(NoticeInfo noticeInfoItemsInfo) {

            }
        });
    }

    private void getCradList() {
        homeBiz.getCardList(new BaseBiz.Callback<List<CreditCardsBean>>() {
            @Override
            public void onSuccess(List<CreditCardsBean> info) {
                if (hotRecommendAdapter != null) {
                    hotRecommendAdapter.setUpBanner(info);
                }
            }

            @Override
            public void onFailure(List<CreditCardsBean> info) {
            }
        });
    }


}